﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace YJKSump
{
	public class MouseHook
	{
		public MouseHook(PlaceSumpForm form)
		{
			this._proc = new MouseHook.LowLevelMouseProc(this.HookCallback);
			this._hookID = IntPtr.Zero;
			this.m_Checkform = form;
		}

		public void HookStart()
		{
			this._hookID = MouseHook.SetWindowsHookEx(12, this._proc, IntPtr.Zero, MouseHook.GetCurrentThreadId());
		}

		public void HookStop()
		{
			MouseHook.UnhookWindowsHookEx(this._hookID);
		}

		[DllImport("kernel32.dll")]
		public static extern uint GetCurrentThreadId();

		[DllImport("user32.dll")]
		public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

		private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
		{
			MouseHook.CWPRETSTRUCT cwpretstruct = (MouseHook.CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(MouseHook.CWPRETSTRUCT));
			if (cwpretstruct.message == 32u)
			{
				short num = this.HIWORD(cwpretstruct.lParam.ToInt32());
				if ((long)num == 512L)
				{
					if (!this.m_Checkform.ClientRectangle.Contains(this.m_Checkform.PointToClient(Cursor.Position)))
					{
						if (this.m_bInForm)
						{
							this.m_Checkform.CheckIfChanged();
						}
						this.m_bInForm = false;
					}
					else
					{
						this.m_bInForm = true;
					}
				}
			}
			return MouseHook.CallNextHookEx(this._hookID, nCode, wParam, lParam);
		}

		private short LOWORD(int value)
		{
			return (short)(value & 65535);
		}

		private short HIWORD(int value)
		{
			return (short)(value >> 16);
		}

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern IntPtr SetWindowsHookEx(int idHook, MouseHook.LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool UnhookWindowsHookEx(IntPtr hhk);

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

		private MouseHook.LowLevelMouseProc _proc;

		private IntPtr _hookID = IntPtr.Zero;

		private PlaceSumpForm m_Checkform;

		private bool m_bInForm;

		private enum Messages
		{
			WM_SETCURSOR = 32,
			WM_MOUSEMOVE = 512
		}

		public struct CWPRETSTRUCT
		{
			public IntPtr lResult;

			public IntPtr lParam;

			public IntPtr wParam;

			public uint message;

			public IntPtr hwnd;
		}

		public enum HookType
		{
			WH_JOURNALRECORD,
			WH_JOURNALPLAYBACK,
			WH_KEYBOARD,
			WH_GETMESSAGE,
			WH_CALLWNDPROC,
			WH_CBT,
			WH_SYSMSGFILTER,
			WH_MOUSE,
			WH_HARDWARE,
			WH_DEBUG,
			WH_SHELL,
			WH_FOREGROUNDIDLE,
			WH_CALLWNDPROCRET,
			WH_KEYBOARD_LL,
			WH_MOUSE_LL
		}

		private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
	}
}
